package com.tianshi.yingxue.controller;

import com.tianshi.yingxue.dto.TwoPageParam;
import com.tianshi.yingxue.entity.Category;
import com.tianshi.yingxue.page.PageParam;
import com.tianshi.yingxue.page.PageResult;
import com.tianshi.yingxue.page.Result;
import com.tianshi.yingxue.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;

/**
 * 类别Controller（对应前端所有接口，路径:/category）
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("/queryOnePage")
    public Result<PageResult<Category>> queryOnePage(@Validated @RequestBody PageParam pageParam) {
        PageResult<Category> pageResult = categoryService.queryOnePage(pageParam);
        return Result.success("一级类别查询成功", pageResult);
    }
    @PostMapping("/queryTwoPage")
    public Result<PageResult<Category>> queryTwoPage(@Validated @RequestBody TwoPageParam twoPageParam) {

        PageResult<Category> pageResult = categoryService.queryTwoPage(twoPageParam);
        return Result.success("二级类别查询成功", pageResult);
    }
    @GetMapping("/queryById")
    public Result<Category> queryById(@RequestParam("id") Integer id) {
        Category category = categoryService.queryById(id);
        return Result.success("类别查询成功", category);
    }
    @PostMapping ("/queryByLevelsCategory")
    public Result<List<Category>> queryByLevels(@RequestParam("levels") Integer levels) {
        // 参数验证
        if (levels == null || levels < 1) {
            return Result.fail("级别参数不能为空且必须大于0");
        }

        // 调用服务层查询
        List<Category> categoryList = categoryService.queryByLevels(levels);
        return Result.success("级别查询成功", categoryList);
    }
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Category category) {
        return categoryService.add(category);
    }
    @PostMapping("/update")

    public Result<Void> update(@RequestBody Category category) {

        categoryService.update(category);
        return Result.success("类别修改成功");
    }

    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody Category category) {
        categoryService.delete(category.getId());
        return Result.success("类别删除成功");
    }
    /**
     * 全局业务异常捕获 - 统一处理业务错误（如"类别不存在"）

    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        System.out.println("业务异常：{}"+ e.getMessage());
        return Result.fail(e.getMessage());
    }
     * 全局异常捕获 - 处理其他未知错误

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        System.out.println("系统异常："+ e);
        return Result.fail("系统异常，请联系管理员");
    }*/
}
